// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import MeshRender2D from "./libs/MeshRender2D";


const { ccclass, property, executeInEditMode, menu } = cc._decorator;

@ccclass
@executeInEditMode
@menu("Mesh/CircleMesh")
export default class CircleMesh extends cc.Component {
    private _offsets: number[] = [];
    private _total = 50;
    private _elapsed: number = 0;
    private _w: number = 1;
    private _a: number = 10;
    private _originPos: cc.Vec2[] = [];
    private _mesh: MeshRender2D;
    onLoad() {
        this._mesh = this.node.getComponent(MeshRender2D);
        let total = this._total;
        let vertexs = [cc.Vec2.ZERO];
        let delta = 360 / total;
        for (let i = 0, len = total; i < len; i++) {
            vertexs.push(cc.v2(Math.cos(cc.misc.degreesToRadians(i * delta)) * 100,
                Math.sin(cc.misc.degreesToRadians(i * delta)) * 100));
            this._originPos.push(vertexs[i + 1].clone());
        }
        this._mesh.vertexs = vertexs;

        let indices = [];
        for (let i = 1, len = total + 1; i < len; i++) {
            indices.push(0);
            indices.push(i);
            indices.push(i < total ? i + 1 : 1);
        }

        this._mesh.indices = indices;

        this._offsets = new Array(total).fill(0);
    }

    protected update(dt: number): void {
        this._elapsed += dt;
        let delta = cc.misc.degreesToRadians(360 / this._total);
        for (let i = 0; i < this._total; i++) {
            let offset = this._a * Math.sin(this._w * this._elapsed + i * delta * 60);
            this._mesh.vertexs[i + 1].normalizeSelf().mulSelf(offset).addSelf(this._originPos[i]);
        }
        this._mesh["setVertsDirty"]();
    }
}   
